<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
    <title>gCalBirthdays</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <style type="text/css">
      .indent {
        margin: 30px 0px 0px 20px;
      }
    </style>

    <!--http://code.google.com/p/gdata-javascript-client/-->
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>

    <!--http://code.google.com/p/gdata-javascript-client/-->
    <script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>

    <!-- jsProgressBarHandler core -->
    <script type="text/javascript" src="../JS/jsProgressBarHandler.js"></script>

    <!--http://phpjs.org/packages/view/396/name:7d67fb58ff9ab58f4d0e4e55221b50e7-->
    <script type="text/javascript" src="../JS/html_funcs.min.js"></script>

    <!--gCalBirthay Javascript functions for HTML and Gadget Version-->
    <script type="text/javascript" src="../JS/gCalBirthdays.js"></script>

    <!--gCalBirthay HTML specific Javascript functions-->
    <script type="text/javascript">

    /*  Copyright (c) 2009 Frank Glaser
     *
     *  This program is free software: you can redistribute it and/or modify
     *  it under the terms of the GNU General Public License as published by
     *  the Free Software Foundation, either version 3 of the License, or
     *  (at your option) any later version.
     *
     *  This program is distributed in the hope that it will be useful,
     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     *  GNU General Public License for more details.
     *
     *  You should have received a copy of the GNU General Public License
     *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
     */

    /* Restrictions on GData JavaScript Client 1.10:
     * - The JavaScript client libraries don't yet support Contacts Data API Version 3.
     *     v2 has no birthday fields
     *     v2 has no support for structured name and postal address
     *     v2 no support for retrieving system groups
     * - Batch operations are not supported by the JavaScript client library.
     *
     * InternetExplorer JScript 5.6 Compatibility
     * - use var instead of const
     * - use for(;;) loop instead of for each (element in array) loop
     */

    //IE JScript 5.6 Compatibility
    // Constants
    var APP_NAME = 'gCalBirthdays';
    var APP_VERSION = '2.03';

    var GOOGLE_FEED_AUTH = 'http://www.google.com/m8/feeds/ http://www.google.com/calendar/feeds/';

    var ALL_CONTACTS = 'All contacts';
    var NEW_CALENDAR = 'New calendar';


    // Load the Google data JS Client Library
    //google.load('gdata', '1.x');
    // Save overhead, only load the necessary service
    google.load("gdata", "1.x", {packages: ['contacts', 'calendar']});

    // Tells the google JS lib to call the init function once loaded
    google.setOnLoadCallback(setupHTML);

    /**
     * This function checks if the user is logged in, and changes the
     * login button and displayed sections accordingly.
     * On successful login it calls the main function.
     */
    function setupHTML(){
      var authButton = $('authButtonID');
      $('versionID').innerHTML = APP_NAME + ' Version: ' + APP_VERSION;

      var token = google.accounts.user.checkLogin(GOOGLE_FEED_AUTH);
      if (token) {
        // User is loged in
        authButton.value = 'Logout';
        $('busyLoaderID').style.display = 'block';
        $('loginNoticeID').style.display = 'none';
        setupService();
        queryGroupsAndCalendars();
      }
      else {
        // User is loged out
        authButton.value = 'Login';
        $('loginNoticeID').style.display = 'block';
        $('settingsFormID').style.display = 'none';
      }
    };

    /**
     * This function is triggered by the login/logout button. If the
     * user is logged in to the app, it logs them out. If the user is
     * logged out to the app, it logs them in.
     */
    function onClickAuthButton(){
      printConsole('Button Auth');

      var token = google.accounts.user.checkLogin(GOOGLE_FEED_AUTH);
      if (token) {
        // User is loged in
        google.accounts.user.logout();
        //TODO
        onclickStop();
      }
      else {
        // User is loged out
        // Use AuthSub Authentication
        token = google.accounts.user.login(GOOGLE_FEED_AUTH);
      }

      setupHTML();
    }

    function showGroups(selId){
      // Clear options
      selectClearOptions('groupSelectID');

      // Add all contacts option
      selectAddOption('groupSelectID', ALL_CONTACTS, '');

      // Iterate through the array of contact groups, and add them to
      // drop down box
      // IE JScript 5.6 Compatibility
      var len = groupList.length;
      for (var ie = 0; ie < len; ie++) {
        var group = groupList[ie];
        selectAddOption('groupSelectID', group.title, group.id);
      }

      // Set selection and size
      selectSetSelectedIndex('groupSelectID', selId);
      selectSetSizeOptions('groupSelectID');
    }


    function showCalendars(selId){
      // Clear options
      selectClearOptions('calendarSelectID');

      // Iterate through the array of contact groups, and add them to
      // drop down box
      // IE JScript 5.6 Compatibility
      var len = calendarList.length;
      for (var ie = 0; ie < len; ie++) {
        var calendar = calendarList[ie];
        selectAddOption('calendarSelectID', calendar.title, calendar.url);
      }

      // Add new calendar option
      selectAddOption('calendarSelectID', NEW_CALENDAR, '');

      // Set selection and size
      selectSetSelectedIndex('calendarSelectID', selId);
      selectSetSizeOptions('calendarSelectID');
    }

    function showSettingsBlock(state){
      // Wait for both queries (queryGroups/queryCalendars) finished
      // Both select boxes (groupSelectID/calendarSelectID) are filled
      if ( states.fingroups == state) {
          showSettingsBlock.groups = true;
      }
      if ( states.fincalendars == state) {
          showSettingsBlock.calendars = true;
      }

      if (showSettingsBlock.groups && showSettingsBlock.calendars) {
        $('busyLoaderID').style.display = 'none';
        $('settingsFormID').style.display = 'block';
      }
    }

    /**
     * Add new calendar.
     */
    function onChangeCalendarSelect(){
      var elSel = $('calendarSelectID');
      if (NEW_CALENDAR == elSel.options[elSel.selectedIndex].text) {
        var calendarName = prompt("Calendar name:", "Birthdays");
        if (calendarName != null && calendarName != "") {
          insertCalendar(calendarName);
        }
        else {
          selectSetSelectedIndex('calendarSelectID', 0);
        }
      }
    }

    /**
     * Query user contacts and events.
     * The queries are processed parallel,
     * they were transfered within transferBirthdays.
     * Compare both:
     *  - Update outdated events
     *  - Insert missing events
     */
    function onclickStart(){
      printConsole('Button Go');

      $('startButtonID').disabled = true;
      $('stopButtonID').disabled = false;
      //$('progressBarId').style.display = 'block';

      // Retrieve Contacts
      var elSelGroup = $('groupSelectID');
      var groupId = new Array();
      // Get all selected groups
      if (0 == elSelGroup.selectedIndex) {
        // GroupId == All contacts
        printConsole('Query Contacts from: ' + elSelGroup.options[elSelGroup.selectedIndex].text);
        groupId[0] = elSelGroup.options[elSelGroup.selectedIndex].value;
      }
      else {
        // GroupId != All contacts
        var len = elSelGroup.length;
        for (var gid=0,elSelId=0; elSelId < len; elSelId++) {
          if (elSelGroup.options[elSelId].selected) {
            printConsole('Query Contacts from: ' + elSelGroup.options[elSelId].text);
            groupId[gid++] = elSelGroup.options[elSelId].value;
          }
        }
      }

      // Retrieve Events
      var elSelCalendar = $('calendarSelectID');
      printConsole('Query Events from: ' + elSelCalendar.options[elSelCalendar.selectedIndex].text);
      var calendarURL = elSelCalendar.options[elSelCalendar.selectedIndex].value;

      queryContactsAndEvents(groupId, calendarURL);
    }

    function onfinishedSync(){
      statemachine = states.finished;
      printConsole('StateMachine: ' + 'finished');
      $('startButtonID').disabled = false;
      $('stopButtonID').disabled = true;
      //$('progressBarId').style.display = 'none';
    }

    function onclickStop(){
      printConsole('Button Cancel');
      statemachine = states.canceled;
      printConsole('StateMachine: ' + 'canceled');
      $('startButtonID').disabled = false;
      $('stopButtonID').disabled = true;
      //$('progressBarId').style.display = 'none';
    }

    </script>
  </head>

  <body>
    <!--Main page-->
    <div class="indent">
      <img src="gCalBirthdays.gif" alt="gCalBirthdays Logo"> <br>

      <p id="versionID">
          Version:
      </p>

      <p>
          Welcome to gCalBirthdays, an app that transfer Your
          Google Contacts birthdays to Your Google Calendar.
      </p>

      <p id="loginNoticeID" style="color:#cc0000; font-weight:bold; display:none">
          Because this is a third-party app that uses your Google
          account authentication, you'll need to grant access to
          it by clicking the "Login" button.
      </p>

      <p>
        <input id="authButtonID" type="button" value="Authenticate" onclick="onClickAuthButton()">
      </p>

      <form id="busyLoaderID" style="display:none">
        <img src="../Images/busyLoader.gif" alt="BusyLoader Image">
      </form>

      <form id="settingsFormID" style="display:none">
        <table cellspacing="0" cellpadding="5">
          <tr valign="bottom">
            <td style="padding-right: 30px">Select Group(s):</td>
            <td style="padding-right: 30px">Select Calendar:</td>
          </tr>
          <tr valign="top">
            <td style="padding-right: 30px">
              <select id="groupSelectID" multiple="multiple" size="4"></select>
            </td>
            <td style="padding-right: 30px">
              <select id="calendarSelectID" size="1" onchange="onChangeCalendarSelect()"></select>
            </td>
          </tr>
        </table>
        <br>
        <input id="startButtonID" type="button" value="Go" onclick="onclickStart()">
        <input id="stopButtonID" type="button" value="Cancel" onclick="onclickStop()" disabled="true">
        <br>
        <br>
        <table id="progressBarId">
          <tr>
            <td>Load Contacts:</td>
            <td><span id="progressBarContactsId" class="progressBar">0%</span></td>
          </tr>
          <tr>
            <td>Load Events:</td>
            <td><span id="progressBarEventsId" class="progressBar">0%</span></td>
          </tr>
          <tr>
            <td>Transfer Birthdays:</td>
            <td><span id="progressBarTransferId" class="progressBar">0%</span></td>
          </tr>
        </table>
      </form>
    </div>

    <!--Google Analytics-->
    <script type="text/javascript">
      var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
      document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
    <script type="text/javascript">
      try {
        var pageTracker = _gat._getTracker("UA-9798979-1");
        pageTracker._trackPageview();
      }
      catch(err) {}
    </script>

  </body>
</html>
